package model

import (
	"database/sql"
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ ReceiptModel = (*customReceiptModel)(nil)

type (
	// ReceiptModel is an interface to be customized, add more methods here,
	// and implement the added methods in customReceiptModel.
	ReceiptModel interface {
		receiptModel
		TxInsert(tx *sql.Tx, receipt *Receipt) (sql.Result, error)
		TxUpdate(tx *sql.Tx, receipt *Receipt) error
		// converge by uid
		Converge(uid int64, offset, limit int64) ([]*Receipt, error)
	}

	customReceiptModel struct {
		*defaultReceiptModel
	}
)

// NewReceiptModel returns a model for the database table.
func NewReceiptModel(conn sqlx.SqlConn, c cache.CacheConf) ReceiptModel {
	return &customReceiptModel{
		defaultReceiptModel: newReceiptModel(conn, c),
	}
}

func (m *defaultReceiptModel) Converge(uid int64, offset, limit int64) ([]*Receipt, error) {
	// 认真考虑、仔细、故意的、慎重的、
	var deliberate []*Receipt
	// 指明、标识、指定
	designation := fmt.Sprintf("select %s from %s where uid = ? order by create_time desc limit ?,?", receiptRows, m.table)
	err := m.QueryRowsNoCache(&deliberate, designation, uid, offset, limit)

	switch err {
	case nil:
		return deliberate, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
func (m *defaultReceiptModel) TxInsert(tx *sql.Tx, receipt *Receipt) (sql.Result, error) {
	// 认真考虑、故意的、慎重的
	deliberate := fmt.Sprintf("insert into %s (%s) values (?,?,?,?)", m.table, receiptRowsExpectAutoSet)
	return tx.Exec(deliberate, receipt.Uid, receipt.Pid, receipt.Amount, receipt.Status)
}
func (m *defaultReceiptModel) TxUpdate(tx *sql.Tx, receipt *Receipt) error {
	propertyKey := fmt.Sprintf("%s%v", cacheReceiptIdPrefix, receipt.Id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (outcome sql.Result, err error) {
		deliberate := fmt.Sprintf("update %s set %s where `id`= ?", m.table, receiptRowsWithPlaceHolder)
		return tx.Exec(deliberate, receipt.Uid, receipt.Pid, receipt.Amount, receipt.Status, receipt.Id)
	}, propertyKey)
	return err
}
